<template>
  <Layout>
    <div class="register-container">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        当前位置：<router-link to="/home">首页</router-link> > 
        <span class="current">{{ tableName === 'volunteers' ? '志愿者注册' : '志愿队伍注册' }}</span>
      </div>
      <div class="tabs">
        <div 
          class="tab-item" 
          :class="{ active: tableName === 'volunteers' }"
          @click="tableName = 'volunteers'"
        >
          <i class="el-icon-user"></i>
          志愿者注册
        </div>
        <div 
          class="tab-item" 
          :class="{ active: tableName === 'organizations' }"
          @click="tableName = 'organizations'"
        >
          <i class="el-icon-office-building"></i>
          志愿队伍注册
        </div>
      </div>
      <div v-if="tableName === 'organizations'" class="form-content">
        <div class="steps">
          <div class="step" v-for="(step, index) in steps" :key="index">
            <div :class="['circle', { active: index === currentStep }]">{{ index + 1 }}</div>
            <div class="label" :class="{ active: index === currentStep }">{{ step }}</div>
            <div class="line" v-if="index < steps.length - 1"></div>
          </div>
        </div>
        <div v-if="currentStep === 0" class="step-content">
          <h3 class="section-title">选择队伍类型</h3>
          <div class="team-types">
            <div class="team-type" v-for="(type, index) in teamTypes" :key="index" :class="{ hover: type.hover }" @mouseenter="type.hover = true" @mouseleave="type.hover = false">
              <div class="type-icon">
                <img :src="type.icon" alt="" class="icon">
              </div>
              <h4>{{ type.title }}</h4>
              <p>{{ type.description }}</p>
              <el-button type="primary" class="register-button" @click="handleTypeSelect(index)">点击注册</el-button>
            </div>
          </div>
          <div class="note">
            <el-alert
              title="注册不同类型的队伍需提交不同的信息和材料，请谨慎选择需要注册的队伍类型。选择错误会导致注册无法通过审核。"
              type="warning"
              show-icon
              :closable="false"
            />
          </div>
        </div>
        <div v-else-if="currentStep === 1" class="step-content">
          <!-- 账户信息表单 -->
          <el-form 
            class="register-form" 
            :model="orgForm"
            :rules="orgRules"
            ref="orgFormRef"
            label-position="right"
            label-width="120px"
          >
            <h3 class="form-title">账号信息</h3>
            <el-form-item label="组织名称：" prop="organizationName">
              <el-input v-model="orgForm.organizationName" placeholder="请输入组织名称">
                <template #prefix><i class="el-icon-office-building"></i></template>
              </el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input v-model="orgForm.password" type="password" placeholder="请输入密码" show-password>
                <template #prefix><i class="el-icon-lock"></i></template>
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码：" prop="password2">
              <el-input v-model="orgForm.password2" type="password" placeholder="请确认密码" show-password>
                <template #prefix><i class="el-icon-lock"></i></template>
              </el-input>
            </el-form-item>
            <div class="form-buttons">
              <el-button type="primary" class="submit-button" @click="nextStep">下一步</el-button>
              <el-button @click="currentStep = 0">返回</el-button>
            </div>
          </el-form>
        </div>
        <div v-else-if="currentStep === 2" class="step-content">
          <!-- 基本信息表单 -->
          <el-form
            class="register-form"
            :model="orgForm"
            :rules="orgRules"
            ref="orgFormRef"
            label-position="right"
            label-width="120px"
          >
            <h3 class="form-title">基本信息</h3>
            <el-form-item label="所属区域：" prop="region">
              <el-select v-model="orgForm.region" placeholder="请选择所属区域">
                <el-option label="南珠东校区" value="南珠东校区"></el-option>
                <el-option label="南珠西校区" value="南珠西校区"></el-option>
                <el-option label="银滩校区" value="银滩校区"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址：" prop="detailedAddress">
              <el-input v-model="orgForm.detailedAddress" placeholder="请输入详细地址">
                <template #prefix><i class="el-icon-map-location"></i></template>
              </el-input>
            </el-form-item>
            <el-form-item label="成立日期：" prop="establishmentDate">
              <el-date-picker
                v-model="orgForm.establishmentDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="人员规模：" prop="personnelScale">
              <el-input-number v-model="orgForm.personnelScale" :min="1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="上级组织：" prop="parentOrganization">
              <el-input v-model="orgForm.parentOrganization" placeholder="请输入上级组织名称" />
            </el-form-item>
            <el-form-item label="组织简介：" prop="organizationProfile">
              <el-input
                type="textarea"
                v-model="orgForm.organizationProfile"
                :rows="4"
                placeholder="请输入组织简介"
              />
            </el-form-item>
            <div class="form-buttons">
              <el-button type="primary" class="submit-button" @click="nextStep">下一步</el-button>
              <el-button @click="currentStep--">返回</el-button>
            </div>
          </el-form>
        </div>
        <div v-else-if="currentStep === 3" class="step-content">
          <!-- 负责人信息 -->
          <el-form
            class="register-form"
            :model="orgForm"
            :rules="orgRules"
            ref="orgFormRef"
            label-position="right" 
            label-width="120px"
          >
            <h3 class="form-title">负责人信息</h3>
            <el-form-item label="负责人姓名：" prop="contactPerson">
              <el-input v-model="orgForm.contactPerson" placeholder="请输入负责人姓名" />
            </el-form-item>
            <template v-if="selectedType === 1">
              <el-form-item label="证件材料：" prop="materialsUrl">
                <el-upload
                  class="upload-demo"
                  action="http://localhost:9090/api/upload/image"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传法人资格证明等相关材料</div>
                  </template>
                </el-upload>
              </el-form-item>
            </template>
            <div class="form-buttons">
              <el-button type="primary" class="submit-button" @click="handleOrgRegister">提交注册</el-button>
              <el-button @click="currentStep--">返回</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div v-else-if="tableName === 'volunteers'" class="form-content">
        <!-- 志愿者注册表单 -->
        <el-form 
          class="register-form volunteer-form" 
          :model="registerForm"
          :rules="rules"
          ref="registerFormRef"
          label-position="right"
          label-width="100px"
        >
          <h3 class="form-title">账号信息</h3>
          <el-form-item label="用户名：" prop="name">
            <el-input v-model="registerForm.name" placeholder="请输入用户名">
              <template #prefix><i class="el-icon-user"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password>
              <template #prefix><i class="el-icon-lock"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码：" prop="password2">
            <el-input v-model="registerForm.password2" type="password" placeholder="请确认密码" show-password>
              <template #prefix><i class="el-icon-lock"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="phoneNumber">
            <el-input v-model="registerForm.phoneNumber" placeholder="请输入手机号">
              <template #prefix><i class="el-icon-mobile-phone"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱">
              <template #prefix><i class="el-icon-message"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="区域：" prop="area">
            <el-input v-model="registerForm.area" placeholder="请选择区域">
              <template #prefix><i class="el-icon-location"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item label="政治面貌：" prop="politicalAffiliation">
            <el-select v-model="registerForm.politicalAffiliation" placeholder="请选择政治面貌">
              <el-option label="中共党员" value="1" />
              <el-option label="预备党员" value="2" />
              <el-option label="共青团员" value="3" />
              <el-option label="群众" value="4" />
            </el-select>
          </el-form-item>
          <el-button type="primary" class="submit-button" @click="handleRegister">注册</el-button>
        </el-form>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Layout from '@/components/Layout.vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const tableName = ref('volunteers')
const registerFormRef = ref()
const orgFormRef = ref()
const selectedType = ref(0)

onMounted(() => {
  const type = route.query.type
  if (type) {
    tableName.value = type
  }
})

const currentStep = ref(0)
const steps = ['选择队伍类型', '账户信息', '基本信息', '负责人信息']
const teamTypes = [
  {
    icon: 'src/assets/images/volunteer.png',
    title: '志愿服务组织',
    description: '在民政部门依法登记成立，以开展志愿服务为宗旨的非营利性组织。',
    hover: false
  },
  {
    icon: 'src/assets/images/volunteer.png',
    title: '其他开展志愿服务活动的法人组织',
    description: '志愿服务组织以外的，依法开展志愿服务活动的法人组织。',
    hover: false
  },
  {
    icon: 'src/assets/images/volunteer.png',
    title: '志愿服务团体',
    description: '经社区或单位同意成立的，以开展志愿服务为宗旨的团体。',
    hover: false
  }
]

const registerForm = ref({
  name: '',
  password: '',
  password2: '',
  email: '',
  phoneNumber: '',
  area: '',
  politicalAffiliation: ''
})

const orgForm = ref({
  organizationName: '',
  password: '',
  password2: '',
  region: '',
  detailedAddress: '',
  establishmentDate: '',
  personnelScale: 1,
  parentOrganization: '',
  organizationProfile: '',
  contactPerson: '',
  organizationType: 0,
  materialsUrl: '',
  status: 0
})

const validatePass2 = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateOrgPass2 = (rule, value, callback) => {
  if (value !== orgForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[0-9]{11}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9+_.-]+@(.+)$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  politicalAffiliation: [
    { required: true, message: '请选择政治面貌', trigger: 'change' }
  ]
}

const orgRules = {
  organizationName: [
    { required: true, message: '请输入组织名称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateOrgPass2, trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请输入所属区域', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  establishmentDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' }
  ],
  personnelScale: [
    { required: true, message: '请输入人员规模', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
  ]
}

const handleTypeSelect = (index) => {
  selectedType.value = index
  orgForm.value.organizationType = index
  currentStep.value = 1
}

const nextStep = async () => {
  try {
    await orgFormRef.value.validate()
    currentStep.value++
  } catch (error) {
    ElMessage.error('请填写完整信息')
  }
}

const handleUploadSuccess = (response) => {
  if (response) {
    orgForm.value.materialsUrl = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!')
  }
  return isLt2M
}

const handleOrgRegister = async () => {
  try {
    await orgFormRef.value.validate()
    
    const response = await axios.post('http://localhost:9090/organizations/register', orgForm.value)

    if (response === '注册成功') {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      console.log(response)
      ElMessage.error(response.data)
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '注册失败')
    } else {
      ElMessage.error('注册失败，请稍后重试')
    }
  }
}

const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()
    
    const response = await axios.post('http://localhost:9090/volunteers/register', {
      name: registerForm.value.name,
      password: registerForm.value.password,
      phoneNumber: registerForm.value.phoneNumber,
      email: registerForm.value.email,
      area: registerForm.value.area,
      politicalAffiliation: registerForm.value.politicalAffiliation
    })

    if (response.data.success) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '注册失败')
    } else {
      ElMessage.error('注册失败，请稍后重试')
    }
  }
}
</script>

<style scoped>
.register-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.breadcrumb {
  padding: 15px 20px;
  background-color: #f8f8f8;
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
  border-radius: 4px;
}

.breadcrumb a {
  color: #e31436;
  text-decoration: none;
  transition: color 0.3s;
}

.breadcrumb a:hover {
  color: #ff4d6a;
}

.breadcrumb .current {
  color: #e31436;
  font-weight: bold;
}

.tabs {
  display: flex;
  border-bottom: 2px solid #e31436;
  margin-bottom: 30px;
}

.tab-item {
  flex: 1;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  font-weight: bold;
  color: #666;
  background-color: #f8f8f8;
  transition: all 0.3s;
  border-radius: 8px 8px 0 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.tab-item:hover {
  background-color: #fff;
  color: #e31436;
}

.tab-item.active {
  background-color: #e31436;
  color: #fff;
}

.form-content {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
}

.steps {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
  position: relative;
  padding: 0 40px;
}

.step {
  text-align: center;
  position: relative;
  z-index: 1;
  flex: 1;
}

.circle {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  background-color: #e4e4e4;
  color: #fff;
  margin: 0 auto 10px;
  font-weight: bold;
  transition: all 0.3s;
}

.circle.active {
  background-color: #e31436;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(227, 20, 54, 0.3);
}

.label {
  font-size: 14px;
  color: #666;
  transition: color 0.3s;
}

.label.active {
  color: #e31436;
  font-weight: bold;
}

.line {
  position: absolute;
  top: 20px;
  left: 50%;
  width: 100%;
  height: 2px;
  background-color: #e4e4e4;
  z-index: 0;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #e31436;
  text-align: center;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 3px;
  background-color: #e31436;
}

.team-types {
  display: flex;
  justify-content: space-between;
  gap: 30px;
  margin-bottom: 30px;
}

.team-type {
  flex: 1;
  padding: 30px;
  border: 1px solid #e4e4e4;
  border-radius: 12px;
  text-align: center;
  background-color: #fff;
  transition: all 0.3s;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.team-type:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  border-color: #e31436;
}

.type-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  background-color: #f8f8f8;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  width: 50px;
  height: 50px;
  transition: transform 0.3s;
}

.team-type:hover .icon {
  transform: scale(1.1);
}

.team-type h4 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.team-type p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
  min-height: 60px;
}

.register-button {
  width: 100%;
  height: 40px;
  border-radius: 20px;
  font-weight: bold;
  transition: all 0.3s;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(227, 20, 54, 0.2);
}

.note {
  margin-top: 30px;
}

.register-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.volunteer-form {
  max-width: 500px;
  padding: 20px;
  margin-bottom: 60px;
}

.form-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.submit-button {
  width: 200px;
  height: 40px;
  border-radius: 20px;
  font-weight: bold;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-alert) {
  border-radius: 8px;
}
</style>
